//
//  CZUserAccountTool.swift
//  SinaBlog
//
//  Created by 李超 on 16/3/22.
//  Copyright © 2016年 lichao. All rights reserved.
//

import UIKit

class CZUserAccountTool: NSObject {
    
    static let shareInstance:CZUserAccountTool = CZUserAccountTool()
    
    private override init() {
        super.init()
        //对象方法只能在调用父类初始化方法后使用,类方法前使用class修饰
       userAccount = loadUserAccountInfo()
    }
    
    var userAccount:CZUserAccount?
    var userLogin:Bool{
        
        get{
            return userAccount != nil
        }
    }
    
    
    
    //加载accesstoken,需要添加加载信息调，让调用者根据加载结果进行处理
    func loadAccessToken(code:String,completion:(error:NSError?) -> ()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
             ]
        CZNetworkTool.shareInstance.requestPost(urlString, parameters: parameters) { (result, error) -> () in
            if error != nil{
                //归档不成功则返回对应的错误信息
                completion(error: error)
                print("error = \(error)")
                return
            }
            self.userAccount = CZUserAccount(dict: result!)
            //归档信息
            self.saveUserAccountInfo()
            //完成归档则回调nil
            completion(error: nil)
        }
    }
    //保存用户信息
    func saveUserAccountInfo() -> Bool{
        if userAccount != nil{
        return NSKeyedArchiver.archiveRootObject(userAccount!, toFile: dataPath)
        }else{
            //值为空
            return false
        }
        
     }
    //加载用户基本的信息
    func loadUserAccountInfo() ->CZUserAccount?{
      //预先获取归档的信息
     let account =  NSKeyedUnarchiver.unarchiveObjectWithFile(dataPath) as? CZUserAccount
        //人为设置过期时间便于调试
        account?.expires_Date = NSDate(timeIntervalSinceNow: 1000)
        //判断归档的信息是否过时和是否为空
        if account != nil && account?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            //不为空，且未过期，则返回归档信息
            return account
        }
        return nil
    }
    //加载用户的头像、昵称等信息
    func loadUserInfo(loadUserInfoCallBack:(error:NSError?) ->Void){
        //确保有值才做下一步
        guard let access_token = CZUserAccountTool.shareInstance.userAccount?.access_token else{
            print("access_token无值")
            return
        }
        //确保有值才做下一步
        guard let uid = CZUserAccountTool.shareInstance.userAccount?.uid else{
            print("uid无值")
            return
        }
        //拼接参数
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token":access_token ,"uid":uid]
        //提交请求
        CZNetworkTool.shareInstance.netManager.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //result为JSON类型数据需要进行类型转换
            let dict = result as? [String : AnyObject]
            //保存保存数据
            self.userAccount?.screen_name = dict?["screen_name"] as? String
            self.userAccount?.avatar_large = dict?["avatar_large"] as? String
            self.saveUserAccountInfo()
            loadUserInfoCallBack(error: nil)
            
            }) { (_, error) -> Void in
                
             loadUserInfoCallBack(error: error)
                
        }
        
    }
    

}
